import numpy as np


# def getImageEncoding():
#     imgPaths = [
#         "data/moving_0/gen_0.png",
#         "data/moving_0/gen_1.png",
#         "data/moving_0/gen_2.png",
#         "data/moving_0/gen_3.png",
#     ]
#     result = []
#     for p in imgPaths:
#         img = cv2.imread(p)
#         singleImgEncode = []
#         for h in range(img.shape[0]):
#             for w in range(img.shape[1]):
#                 if np.sum(img[h, w]) > 0:
#                     singleImgEncode.append(h * 10 + w)
#         result.append(singleImgEncode)
#     return result


class ObjectGeneration:

    def __init__(self, objectGenParams):
        self.numObjects = objectGenParams['numObjects']
        self.featuresPerObject = objectGenParams['featuresPerObject']
        self.objectWidth = objectGenParams['objectWidth']
        self.numFeatures = objectGenParams['numFeatures']
        self.featureDistribution = objectGenParams['featureDistribution']
        self.featureScale = objectGenParams['featureScale']
        self.featureNames = [str(i) for i in range(self.numFeatures)]

    def arrangeFeatures(self, allObjectFeatures):
        objects = []
        for o, objectFeatures in enumerate(allObjectFeatures):
            positions = np.random.permutation(range(self.objectWidth ** 2))[0: len(objectFeatures)]
            objects.append({
                "features": [{"left": (pos % self.objectWidth) * self.featureScale,
                              "top": int(pos / self.objectWidth) * self.featureScale,
                              "width": self.featureScale,
                              "height": self.featureScale,
                              "name": str(feat)}
                             for pos, feat in zip(positions, objectFeatures)],
                "name": str(o)})
        return objects

    def generateObjectFeatures(self):
        if self.featureDistribution == "AllFeaturesEqual_Replacement":
            return np.random.randint(self.numFeatures, size=(self.numObjects, self.featuresPerObject), dtype=np.int32)

    def generateObjects(self):
        assert self.featuresPerObject <= (self.objectWidth ** 2)
        objectFeatures = self.generateObjectFeatures()
        return self.arrangeFeatures(objectFeatures)

